package club.pinea.session;

import club.pinea.interfaces.MessageCallback;
import club.pinea.proto.BasicProto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 回调函数容器
 */
public class CallbackContainer {

    static Logger logger = LoggerFactory.getLogger(CallbackContainer.class);

    private static Map<Integer, MessageCallback> callbackMap = new ConcurrentHashMap<>();

    /**
     * 往容器中添加回调函数管理
     *
     * @param callback
     */
    public static synchronized void putCallback(Integer order, MessageCallback callback) {
        callbackMap.put(order, callback);
    }

    /**
     * 消息执行回调
     *
     * @param order
     * @param message
     */
    public static void doCallback(Integer order, BasicProto.BaseMessage message) {
        try {
            if (order != null) {
                // request比response大1
                order++;
            }
            MessageCallback callback = callbackMap.remove(order);
            if (callback == null) {
                logger.info("处理失败，没有待处理的回调函数：" + order);
                return;
            }
            callback.doMessageBack(message);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
